<?php

namespace app\backend\service;

use app\common\model\ConvertModel;
use app\common\model\MemberModel;
use app\common\model\MoneyCashModel;
use app\common\RootService;
use app\common\service\PayService;

class CashService extends RootService
{
    /**
     * @return array
     * @throws \app\common\RootException
     */
    public function labelData()
    {
        return ['stateLabel' => MoneyCashModel::$stateLabel, 'typeLabel' => MoneyCashModel::$typeLabel,
            'convertList' => $this->convertSelect(), 'auditList' => AdminService::adminNames(0, true),
            'bindType' => MemberModel::$bindType, 'payLabel' => MoneyCashModel::$payLabel,
            'stateEdit' => MoneyCashModel::$stateEdit, 'currencyLabel' => ConvertModel::$currencyLabel];
    }

    /**
     * 筛选结果
     * @param array $params
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function lists(array $params)
    {
        // 提现列表
        $cashList = $this->page($this->cashModel($params)->order(['mc.id' => 'desc']));
        $cashList['data'] = $this->dataFormat($cashList['data']);
        return $cashList;
    }

    /**
     * 审核
     * @param array $params
     * @return array
     * @throws \app\common\RootException
     */
    public function edit(array $params)
    {
        $payApi = env('PAY_API');
        try {
            // 提现失败
            if (empty($params['state'])) {
                empty($payApi) && (new PayService())->cashFailed($params['id'], $params['notify']);
            }
            // 手工打款：禁用账号不能提现
            if (in_array($params['state'], [2])) {
                empty($payApi) && (new PayService())->cashPay($params['id']);
            }
            empty($payApi) || httpPostJson($payApi, ['cashId' => $params['id'], 'state' => $params['state'], 'token' => env('CSRF_KEY')]);
        } catch (\Exception $e) {
            $this->errorException($e->getMessage());
        }
        // 修改状态
        $renewData = ['audit_id' => adminInfo('id'), 'state' => $params['state'], 'id' => $params['id'],
            'audit_time' => date('Y-m-d H:i:s'), 'remark' => $params['remark'], 'reason' => $params['notify']];
        MoneyCashModel::update($renewData);
        return ['msg' => '操作成功', 'preload' => true];
    }

    /**
     * 提现详情
     * @param int $cashId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail(int $cashId)
    {
        $info = MoneyCashModel::where(['id' => $cashId])->with(['notify'])->find()->toArray();
        // 通知内容
        empty($info['notify']['notify']) && $info['notify']['notify'] = $info['reason'];
        return $info;
    }

    /**
     * 套餐列表
     * @return array
     * @throws \app\common\RootException
     */
    protected function convertSelect()
    {
        $convertList = ConvertModel::column('name, quantity, currency', 'id');
        array_walk($convertList, function (&$row) {
            $row = str_replace('%s', $row['quantity'], $row['name']);
        });
        return $convertList;
    }

    /**
     * 数据处理
     * @param array $cashList
     * @return array
     * @throws \app\common\RootException
     */
    protected function dataFormat(array $cashList)
    {
        $labelData = $this->labelData();
        array_walk($cashList, function (&$row) use ($labelData) {
            $row['stateLabel'] = $labelData['stateLabel'][$row['state']] ?? '--';
            empty($row['type']) && $row['receipt'] .= 'đ';
            $row['typeLabel'] = $labelData['typeLabel'][$row['type']] ?? '--';
            $row['currencyLabel'] = $labelData['currencyLabel'][$row['currency']] ?? '--';
            $row['bindType'] = $labelData['bindType'][$row['bind_type']] ?? '--';
            $row['adminName'] = $labelData['auditList'][$row['audit_id']] ?? '--';
        });
        return $cashList;
    }

    /**
     * 筛选条件
     * @param array $params
     * @return array
     */
    protected function searchWhere(array $params)
    {
        // 筛选包含提现中的状态
        isset($params['state']) && $params['state'] == 1 && $params['state'] = '1,2';
        // 用户ID筛选
        empty($params['memberId']) || $where[] = ['m.id', '=', $params['memberId']];
        // 收款账号筛选
        empty($params['invite']) || $where[] = ['m.invite', 'like', $params['invite'] . '%'];
        // 收款账号筛选
        empty($params['account']) || $where[] = ['mc.account', 'like', $params['account'] . '%'];
        // 交易日期筛选
        empty($params['updateTime']) || $where[] = ['mc.update_time', 'between', betweenDate($params['updateTime'])];
        // 钱包类型筛选
        condition($params['type'] ?? '') && $where[] = ['mc.type', 'in', explode(',', $params['type'])];
        // 状态筛选
        condition($params['state'] ?? '') && $where[] = ['mc.state', 'in', explode(',', $params['state'])];
        // 提现状态筛选
        condition($params['auditId'] ?? '') && $where[] = ['mc.audit_id', 'in', explode(',', $params['auditId'])];
        // 收款方式筛选
        condition($params['currency'] ?? '') && $where[] = ['mc.currency', 'in', explode(',', $params['currency'])];
        // 提现套餐筛选
        condition($params['convertId'] ?? '') && $where[] = ['mc.convert_id', 'in', explode(',', $params['convertId'])];
        return $where ?? [];
    }

    /**
     * 统计提现金额
     * @param array $params
     * @return mixed
     */
    protected function cashCensus(array $params)
    {
        $where = $this->searchWhere($params);
        $where[] = ['state', '=', 3];
        // 筛选字段
        $fields = [count('distinct member_id'), ];
        // 筛选结果
        return  MoneyCashModel::alias('mc')->join(['sys_member' => 'm'], 'mc.member_id = m.id', 'left')
            ->where($where)->field($fields);
    }

    /**
     * 提现模型
     * @param array $params
     * @return MoneyCashModel
     */
    protected function cashModel(array $params)
    {
        // 筛选字段
        $fields = ['m.id', 'm.avatar', 'm.invite', 'm.account', 'mc.id mcid', 'mc.member_id', 'mc.amount', 'mc.audit_id',
            'mc.state', 'mc.receipt', 'mc.type', 'mc.account payAccount', 'mc.create_time', 'mc.update_time', 'mc.diamond',
            'm.email', 'm.bind_type', 'm.state memberState', 'mc.currency'];
        // 筛选结果
        return  MoneyCashModel::alias('mc')->join(['sys_member' => 'm'], 'mc.member_id = m.id', 'left')
            ->where($this->searchWhere($params))->field($fields);
    }
}